<template>
  <div class="question-history">
    <el-card>
      <template #header>
        <h2>问题记录</h2>
      </template>

      <el-form :inline="true" class="filter-form">
        <el-form-item label="用户ID">
          <el-input
            v-model="filters.userId"
            placeholder="输入用户ID筛选"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="historyList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="question" label="问题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="answer" label="回答" min-width="250" show-overflow-tooltip />
        <el-table-column prop="hasKnowledge" label="是否有知识" width="120">
          <template #default="{ row }">
            <el-tag :type="row.hasKnowledge ? 'success' : 'warning'">
              {{ row.hasKnowledge ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="提问时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: center"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="问题详情"
      width="60%"
    >
      <div v-if="currentRecord">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID">{{ currentRecord.id }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentRecord.userId }}</el-descriptions-item>
          <el-descriptions-item label="问题">{{ currentRecord.question }}</el-descriptions-item>
          <el-descriptions-item label="回答">{{ currentRecord.answer }}</el-descriptions-item>
          <el-descriptions-item label="是否有知识">
            <el-tag :type="currentRecord.hasKnowledge ? 'success' : 'warning'">
              {{ currentRecord.hasKnowledge ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="知识来源" v-if="currentRecord.sources">
            <el-tag
              v-for="(source, index) in parseSourcesArray(currentRecord.sources)"
              :key="index"
              style="margin-right: 5px"
            >
              {{ source }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提问时间">
            {{ formatDate(currentRecord.createdAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getHistory } from '../api/qa'

const historyList = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const currentRecord = ref(null)

const filters = ref({
  userId: ''
})

const pagination = ref({
  page: 1,
  size: 10,
  total: 0
})

const fetchHistory = async () => {
  loading.value = true
  try {
    const userId = filters.value.userId ? parseInt(filters.value.userId) : null
    const response = await getHistory(pagination.value.page, pagination.value.size, userId)
    
    historyList.value = response.records || response.content || []
    pagination.value.total = response.total || 0
  } catch (error) {
    ElMessage.error('获取问题记录失败：' + (error.message || '未知错误'))
    console.error('获取问题记录失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.value.page = 1
  fetchHistory()
}

const handleReset = () => {
  filters.value.userId = ''
  pagination.value.page = 1
  fetchHistory()
}

const handlePageChange = (page) => {
  pagination.value.page = page
  fetchHistory()
}

const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.page = 1
  fetchHistory()
}

const handleViewDetail = (row) => {
  currentRecord.value = row
  detailDialogVisible.value = true
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const parseSourcesArray = (sources) => {
  if (!sources) return []
  if (Array.isArray(sources)) return sources
  try {
    return JSON.parse(sources)
  } catch {
    return []
  }
}

onMounted(() => {
  fetchHistory()
})
</script>

<style scoped>
.question-history {
  max-width: 1400px;
  margin: 0 auto;
}

.filter-form {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
}

.el-table {
  margin-top: 16px;
}
</style>
